package com.mayikt.zuul.filter;

import com.mayikt.zuul.build.GatewayDirector;
import com.mayikt.zuul.handler.ResponsibilityClient;
import com.mayikt.zuul.util.RequestUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Configuration
public class GatewayFilter extends ZuulFilter {
    @Autowired
    private ResponsibilityClient responsibilityClient;
    @Autowired
    private GatewayDirector gatewayDirector;
//    @Value("${blackIpList}")
//    private String blackIpList;
    @Value("${server.port}")
    private String ip;
    /**
     * 请求之前进行业务逻辑处理
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext rct = RequestContext.getCurrentContext();
        //1.获取请求对象
        HttpServletRequest request = rct.getRequest();
        HttpServletResponse response = rct.getResponse();

        //2.校验黑名单和校验参数
//         gatewayDirector.direcot(rct,RequestUtil.getIpAddr(request),response,request) ;
        /**
         * 责任链模式校验黑名单和校验参数
         */
        responsibilityClient.responsibility(rct,RequestUtil.getIpAddr(request),response);
        // 3. 过滤请求参数、防止XSS攻击
        Map<String, List<String>> filterParameters = filterParameters(request, rct);
        rct.setRequestQueryParams(filterParameters);
        return null;
    }


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤参数
     */
    private Map<String, List<String>> filterParameters(HttpServletRequest request, RequestContext ctx) {
        Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
        if (requestQueryParams == null) {
            requestQueryParams = new HashMap<>();
        }
        Enumeration em = request.getParameterNames();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            ArrayList<String> arrayList = new ArrayList<>();
            // 将参数转化为html参数 防止xss攻击 < 转为&lt;
            arrayList.add(StringEscapeUtils.escapeHtml(value));
            requestQueryParams.put(name, arrayList);
        }
        return requestQueryParams;
    }
}
